package com.trainingcloud.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

import com.trainingcloud.entity.Document;
import com.trainingcloud.exception.DAOException;

public class FavoriteDAO extends BaseDAO
{
	public boolean isFavorited(int userId, int documentId) throws DAOException
	{
		Connection connection = getConnection();
		try 
		{
			PreparedStatement query = connection.prepareStatement("SELECT * FROM t_favorite WHERE user_id=? AND document_id=?");
			query.setInt(1, userId);
			query.setInt(2, documentId);
			ResultSet rs = query.executeQuery();
			if(rs.next())
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		catch(SQLException e)
		{
			throw new DAOException(e);
		}
		finally
		{
			try
			{
				connection.close();
			}
			catch (SQLException e) 
			{
				throw new DAOException(e);
			}
		}
	}
	
	public void insertFavorite(int userId, int documentId) throws DAOException
	{
		Connection connection = getConnection();
		try 
		{
			PreparedStatement query = connection.prepareStatement("SELECT * FROM t_favorite WHERE user_id=? AND document_id=?");
			query.setInt(1, userId);
			query.setInt(2, documentId);
			ResultSet rs = query.executeQuery();
			if(rs.next())
			{
				// Already favorite it.
			}
			else
			{
				query = connection.prepareStatement("INSERT INTO t_favorite (user_id, document_id) VALUES (?, ?)");
				query.setInt(1, userId);
				query.setInt(2, documentId);
				if(!query.execute() && query.getUpdateCount()==1)
				{
					// Success
				}
				else
				{
					throw new DAOException("Insert into t_favorite failed.");
				}
			}
		}
		catch(SQLException e)
		{
			throw new DAOException(e);
		}
		finally
		{
			try
			{
				connection.close();
			}
			catch (SQLException e) 
			{
				throw new DAOException(e);
			}
		}
	}
	
	public void deleteFavorite(int userId, int documentId) throws DAOException
	{
		Connection connection = getConnection();
		try 
		{
			PreparedStatement query = connection.prepareStatement("SELECT * FROM t_favorite WHERE user_id=? AND document_id=?");
			query.setInt(1, userId);
			query.setInt(2, documentId);
			ResultSet rs = query.executeQuery();
			if(rs.next())
			{
				query = connection.prepareStatement("DELETE FROM t_favorite WHERE user_id=? AND document_id=?");
				query.setInt(1, userId);
				query.setInt(2, documentId);
				if(!query.execute() && query.getUpdateCount()==1)
				{
					// Success
				}
				else
				{
					throw new DAOException("Delete from t_favorite failed.");
				}
			}
			else
			{
				// Already not favorite it.
			}
		}
		catch(SQLException e)
		{
			throw new DAOException(e);
		}
		finally
		{
			try
			{
				connection.close();
			}
			catch (SQLException e) 
			{
				throw new DAOException(e);
			}
		}
	}
}
